package com.example.demo.leetcode.classics150;

import java.util.ArrayList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _22N字形变换
 * @description
 * @date 2023/07/15 8:14
 * <p>
 * ******************************************************
 */
public class _22N字形变换 {

    public String convert(String s, int numRows) {
        int length = s.length();
        if (numRows == 1) {
            return s;
        }
        List<StringBuilder> rows = new ArrayList<>(numRows);
        for (int i = 0; i < numRows; i++) {
            rows.add(new StringBuilder());
        }
        // 假设numRows=4，前n个字符应当按下列规矩分布在对应层数：1234321234
        int row = 0;
        boolean flag = true;
        for (int i = 0; i < length; i++) {
            rows.get(row).append(s.charAt(i));
            if (i != 0 && (row % numRows == 0 || row % numRows == numRows - 1)) {
                flag = !flag;
            }
            if (flag) {
                row++;
            } else {
                row--;
            }
        }
        StringBuilder sb = new StringBuilder();
        rows.forEach(sb::append);
        return sb.toString();
    }

    public static void main(String[] args) {
        _22N字形变换 s = new _22N字形变换();
        System.out.println(s.convert("PAYPALISHIRING", 3));
    }

}
